package cn.zkteco.doordu.service;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.ble.api.EncodeUtil;

import java.util.List;

import cn.zkteco.doordu.common.SampleGattAttributes;
import cn.zkteco.doordu.proxy.LeProxy;
import cn.zkteco.doordu.utils.TransformUtil;

/**
 * Created by Administrator on 2017/10/11.
 */

public class BleService extends Service {

    private static final String TAG = "BleService---------->";

    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    private String deviceAddress;
    private BluetoothGatt mBluetoothGatt;

    private final IBinder mBinder = new LocalBinder();


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        close();
        return super.onUnbind(intent);
    }

    public boolean initialize() {
        if (mBluetoothManager == null) {
            mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
            if (mBluetoothManager == null) {
                Log.e(TAG, "Unable to initialize BluetoothManager.");
                return false;
            }
        }

        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
            return false;
        }

        return true;
    }

    public boolean connect(String address) {
        if (mBluetoothAdapter == null || address == null) {
            Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
            return false;
        }
        if (deviceAddress != null && mBluetoothGatt != null) {
            Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
            return mBluetoothGatt.connect();
        }

        final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        if (device == null) {
            Log.w(TAG, "Device not found.  Unable to connect.");
            return false;
        }
        close();
        mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
        Log.d(TAG, "Trying to create a new connection.");
        deviceAddress = address;
        return true;
    }

    private void close() {
        if (mBluetoothGatt == null) {
            return;
        }
        mBluetoothGatt.close();
        mBluetoothGatt = null;
    }

    public List<BluetoothGattService> getGattServices() {
        if (mBluetoothGatt != null) {
            return mBluetoothGatt.getServices();
        } else {
            return null;
        }

    }


    public class LocalBinder extends Binder {
        public BleService getService() {
            return BleService.this;
        }
    }


    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

        @Override
        public void onPhyRead(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {
            super.onPhyRead(gatt, txPhy, rxPhy, status);
            System.out.println("------->onPhyRead");
        }

        @Override
        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
            super.onReadRemoteRssi(gatt, rssi, status);
            System.out.println("------->onReadRemoteRssi");
        }

        @Override
        public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
            super.onReliableWriteCompleted(gatt, status);
            System.out.println("------->onReliableWriteCompleted");
        }

        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
//            switch (newState) {
//                case BluetoothProfile.STATE_CONNECTED:
//                    sendBroadcast(new Intent(LeProxy.ACTION_GATT_CONNECTED));
//                    gatt.discoverServices();
//                    break;
//                case BluetoothProfile.STATE_DISCONNECTED:
//                    sendBroadcast(new Intent(LeProxy.ACTION_GATT_DISCONNECTED));
//                    Log.v(TAG, "取消连接");
//                    break;
//                case BluetoothProfile.STATE_CONNECTING:
//                    sendBroadcast(new Intent(LeProxy.ACTION_GATT_CONNECTING));
//                    Log.v(TAG, "正在连接");
//                    break;
//                case BluetoothProfile.STATE_DISCONNECTING:
//                    sendBroadcast(new Intent(LeProxy.ACTION_GATT_DISCONNECTING));
//                    Log.v(TAG, "正在取消连接");
//                    break;
//            }
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                gatt.discoverServices();
                System.out.println("------>连接成功");
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                sendBroadcast(new Intent(LeProxy.ACTION_GATT_SERVICES_DISCOVERED));
                System.out.println("------->扫描到服务");
            }
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            byte[] value = characteristic.getValue();
            System.out.println("------->读特性值:" + TransformUtil.byteArrayToString(value));
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);
//            byte[] b = characteristic.getValue();
//            String a = TransformUtil.byteArrayToString((new EncodeUtil()).decodeMessage(b));
//            System.out.println("-------->写特征" + a);
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
            byte[] b = characteristic.getValue();
            byte[] decodeB = (new EncodeUtil()).decodeMessage(b);
            String cmd = TransformUtil.byteArrayToString(decodeB);
            System.out.println("-------->特征改变:" + cmd);
            updateBroadcast(decodeB);
        }

        @Override
        public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorRead(gatt, descriptor, status);
            byte[] b = descriptor.getValue();
            System.out.println("-------->读描述符:" + TransformUtil.byteArrayToString(b));

        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorWrite(gatt, descriptor, status);
            byte[] b = descriptor.getValue();
            System.out.println("-------->写描述符:" + TransformUtil.byteArrayToString(b));
        }

    };

    private void updateBroadcast(byte[] cmd) {
        Intent i = new Intent(LeProxy.AVAILABLE_DATA);
        i.putExtra(LeProxy.EXTRA_DATA, cmd);
        sendBroadcast(i);
    }


    /**
     * 打开通知通道
     */
    public void enableNotification() {
        if (mBluetoothGatt == null) {
            return;
        }
        BluetoothGattService service = mBluetoothGatt.getService(SampleGattAttributes.USER_SERVICE_UUID);
        BluetoothGattCharacteristic characteristic;
        if (service != null) {
            characteristic = service.getCharacteristic(SampleGattAttributes.READ_NOTIFY_UUID);
        } else {
            return;
        }
        boolean set = mBluetoothGatt.setCharacteristicNotification(characteristic, true);
        Log.d(TAG, " setnotification = " + set);

        for (BluetoothGattDescriptor dp : characteristic.getDescriptors()) {
            dp.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            boolean success = mBluetoothGatt.writeDescriptor(dp);
            Log.d(TAG, "writing enable descriptor:" + success);
        }
    }

    public void enableRead() {
        if (mBluetoothGatt == null) {
            return;
        }
        BluetoothGattService service = mBluetoothGatt.getService(SampleGattAttributes.USER_SERVICE_UUID);
        BluetoothGattCharacteristic characteristic;
        if (service != null) {
            characteristic = service.getCharacteristic(SampleGattAttributes.READ_NOTIFY_UUID);
        } else {
            return;
        }
        mBluetoothGatt.readCharacteristic(characteristic);
    }

    public void enableIndication() {
        if (mBluetoothGatt == null) {
            return;
        }
        BluetoothGattService service = mBluetoothGatt.getService(SampleGattAttributes.USER_SERVICE_UUID);
        BluetoothGattCharacteristic characteristic;
        if (service != null) {
            characteristic = service.getCharacteristic(SampleGattAttributes.READ_NOTIFY_UUID);
        } else {
            return;
        }
        boolean set = mBluetoothGatt.setCharacteristicNotification(characteristic, true);
        Log.d(TAG, " setnotification = " + set);

        for (BluetoothGattDescriptor dp : characteristic.getDescriptors()) {
            dp.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
            boolean success = mBluetoothGatt.writeDescriptor(dp);
            Log.d(TAG, "writing enable descriptor:" + success);
        }
    }


    public void sendCmd(byte[] cmd) {
        System.out.println("------>发送数据:"+TransformUtil.byteArrayToString(cmd));
        int packages = packagesCount(cmd.length);
        BluetoothGattService service = mBluetoothGatt.getService(SampleGattAttributes.USER_SERVICE_UUID);
        if (service == null)
            return;
        BluetoothGattCharacteristic characteristic = service.getCharacteristic(SampleGattAttributes.READ_WRITE_NOTIFY_UUID);

        if (characteristic == null) {
            return;
        }
        for (int i = 1; i <= packages; i++) {
            byte[] newCmd = getPackagesData(cmd, i);
            characteristic.setValue((new EncodeUtil()).encodeMessage(newCmd));
            mBluetoothGatt.writeCharacteristic(characteristic);
        }

    }

    /**
     * 获取每个包中的数据,未生成校验值时最大的长度是16
     *
     * @param pack     数据源
     * @param position 第几个包
     * @return byte[]
     */
    private byte[] getPackagesData(byte[] pack, int position) {

        if (pack.length <= 17) {
            return pack;
        } else {
            byte[] newPack;
            if (pack.length <= 17 * position) {
                newPack = new byte[pack.length - 17 * (position - 1)];

            } else {
                newPack = new byte[17];

            }
            for (int i = 17 * (position - 1); i < 17 * position; i++) {
                if (i < pack.length) { //不能超出数据长度
                    newPack[i - 17 * (position - 1)] = pack[i];
                }
            }
            return newPack;
        }
    }


    private int packagesCount(int cmd) {
        int packages = cmd / 17;
        int remain = cmd % 17;
        if (remain == 0) {
            return packages;
        } else {
            return packages + 1;
        }
    }

    public void sendCmdd(byte[] cmd) {

        BluetoothGattService service = mBluetoothGatt.getService(SampleGattAttributes.USER_SERVICE_UUID);
        if (service == null)
            return;
        BluetoothGattCharacteristic characteristic = service.getCharacteristic(SampleGattAttributes.READ_WRITE_NOTIFY_UUID);

        if (characteristic == null) {
            return;
        }
        characteristic.setValue((new EncodeUtil()).encodeMessage(cmd));
        mBluetoothGatt.writeCharacteristic(characteristic);

//        byte[] package2 = new byte[]{(byte) 0xFF, (byte) 0xFF, (byte) 0x03, (byte) 0x00,(byte)0x06};
//        characteristic.setValue((new EncodeUtil()).encodeMessage(package2));
//        mBluetoothGatt.writeCharacteristic(characteristic);
    }


}
